//
//  TMGFlowViewController.m
//  TMGold
//
//  Created by Mac on 2017/12/13.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "TMGNewMonthProductdetailController.h"
#import "TMMenuControl.h"
#import "TMGUserTableViewCell.h"
#import "TMGFlowMoreTableViewCell.h"
#import "TMGBuyGoldViewController.h"
#import "NSCalendar+STCalendarTool.h"
#import "TMGDetailTableViewCell.h"
@interface TMGNewMonthProductdetailController ()
@property(nonatomic, strong) NSArray                               *titleArray;
@property(nonatomic, strong) STSegementButton                      *segementButton;
@property(nonatomic, strong) UIView                                *topView;
@property(nonatomic, strong) NSArray<STTableEasyModel*>            *productArray;
@property(nonatomic, strong) NSMutableArray                               *userArray;
@property(nonatomic, strong) NSArray                               *moreArray;
@property(nonatomic, strong) TMGProductDetailModel                     *detailModel;
@end

@implementation TMGNewMonthProductdetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"产品详情";
    _titleArray = @[@"产品详情",@"购买人数"];
    [self configSubView];
    [self configTableFooter];
  //  [self configBootomView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (IOS11 && [self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.tableView setContentInsetAdjustmentBehavior:@(2)];
    }
    self.tableView.frame = CGRectMake(0, [TMUtils navgationBarBootom], UIScreenWidth, [TMUtils tabBarTop] + 49 - [TMUtils navgationBarBootom]);
    
    [self.tableView registerClass:[TMGUserTableViewCell class] forCellReuseIdentifier:@"userCell"];
    [self.tableView registerClass:[TMGFlowMoreTableViewCell class] forCellReuseIdentifier:@"moreCell"];
    [self sendGoodDetailReqeust];
    [self sendGoodPeopleBuyReqeust];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.tableView registerClass:[TMGDetailTableViewCell class] forCellReuseIdentifier:@"detailCell"];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar st_setBackgroundColor:monthColor];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar st_setBackgroundColor:TM_orangeColor];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)reloadData{
    NSString * free = [NSString stringWithFormat:@"%@元",self.detailModel.fee];
    
    NSString * saleFree = [NSString stringWithFormat:@"%@元/克",self.detailModel.fee_sale];
    
    NSString * rate = self.detailModel.year_rate_from;
    if (self.detailModel.year_rate_to.floatValue > 0.1) {
        rate = [NSString stringWithFormat:@"%@~%@",self.detailModel.year_rate_from,self.detailModel.year_rate_to];
    }
    rate = [NSString stringWithFormat:@"%@%%",rate];
    NSString * buyStratr = [NSString stringWithFormat:@"%@元起购",
                            @(self.detailModel.buy_start.integerValue)];
    
    
    NSDate * date = [NSDate date].st_localDate;
    
    NSDate * tormmorDate = [NSCalendar st_nextDayDate:date];
    
    NSDate * endDate = [date copy];
    for (NSInteger i = 0; i <  self.detailModel.day_number.integerValue; i ++) {
        endDate = [NSCalendar st_realNextMonth:endDate];
    }
    NSDate * shouyiDate = [NSCalendar st_nextDayDate:endDate];
    
//    NSString * buyStratr = [NSString stringWithFormat:@"%@元",
//                            @(self.detailModel.buy_start.integerValue)];
    
    self.productArray = @[
                          [[STTableEasyModel alloc] initWithTextString:@"产品说明" detailString:@"本息复投,每月可预约赎回"],
                          [[STTableEasyModel alloc] initWithTextString:@"手续费"
                                                          detailString:free],
                          [[STTableEasyModel alloc] initWithTextString:@"买入期限"
                                                          detailString:[NSString stringWithFormat:@"%@(月)",self.detailModel.day_number]],
                          [[STTableEasyModel alloc] initWithTextString:@"风险类型" detailString:@"稳健型"],
                          [[STTableEasyModel alloc] initWithTextString:@"预计黄金收益率" detailString:rate],
                          [[STTableEasyModel alloc] initWithTextString:@"购买截止"
                                                          detailString:self.detailModel.deadline],
                          [[STTableEasyModel alloc] initWithTextString:@"计息起始日"
                                                          detailString:tormmorDate.st_yyyyMMddByLineWithDate],
                          [[STTableEasyModel alloc] initWithTextString:@"计息结束日"
                                                          detailString:endDate.st_yyyyMMddByLineWithDate],
                          [[STTableEasyModel alloc] initWithTextString:@"收益发放日"
                                                          detailString:shouyiDate.st_yyyyMMddByLineWithDate],
                          [[STTableEasyModel alloc] initWithTextString:@"收益发放方式" detailString:@"本息复投"],
                           [[STTableEasyModel alloc] initWithTextString:@"计息期" detailString:[NSString stringWithFormat:@"%@个月",self.detailModel.day_number]],
                         [[STTableEasyModel alloc] initWithTextString:@"起购金额" detailString:buyStratr],
                          [[STTableEasyModel alloc] initWithTextString:@"单次购买上限"
                                                          detailString:@"不限"]];
    
    
    self.moreArray = @[@"",@"",@""];
    [self.tableView reloadData];
}
- (UIView*)headerWithTitle:(NSString*)title des:(NSString*)desStr{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 40)];
    view.backgroundColor = [UIColor whiteColor];
    UIView * header = [TMUtils headerViewWithTitle:title color:monthColor];
    [view addSubview:header];
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(15, header.bottom + 10, UIScreenWidth - 30, 44)
                                                     text:desStr
                                                textColor:FirstTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [NSString lableAutoAdjustheightWithLabel:titleLable];
    [view addSubview:titleLable];
    view.height = titleLable.bottom + 30;
    return view;
}
- (void)configTableFooter{
    
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    
    UIView  *comeForm = [self headerWithTitle:@"收益来源" des:@"您投资的资金将于购买知名平台的，安全性极高的债券，您的收益来自于债券产生的收益"];
    [footer addSubview:comeForm];
    comeForm.top = 10;
    
    TMGGoldDetailView  * view = [[TMGGoldDetailView alloc] initWithFrame:CGRectMake(0, comeForm.bottom, UIScreenWidth, 30)];
    [footer addSubview:view];
//    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, view.bottom + 10, UIScreenWidth, 44)
//                                                     text:[NSString stringWithFormat:@"剩余可购买金额%@元",self.detailModel.is_sell]
//                                                textColor:TM_secendTextColor
//                                                     font:14
//                                              isSizetoFit:NO
//                                            textAlignment:NSTextAlignmentCenter];
//    [footer addSubview:titleLable];
    footer.height = view.bottom  + 10;
    self.tableView.tableFooterView = footer;
}
- (void)configSubView{
    
    UIView * topView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, UIScreenWidth, 100)];
    topView.backgroundColor = [UIColor whiteColor];

    NSString * rate = self.detailModel.year_rate_from;
    if (self.detailModel.year_rate_to.floatValue > 0.1) {
        rate = [NSString stringWithFormat:@"%@~%@",self.detailModel.year_rate_from,self.detailModel.year_rate_to];
    }

    //简介
    UIView * product = [self headerWithTitle:@"产品简介"
                                         des:[NSString stringWithFormat:@"%@是黄金口袋推出的稳健性产品，年化率逐月提升%@%@\n每个月可在我的-投资计划-月月有息-再投中预约退出（每月退出的前一天的22点前可以预约当月赎回），预约退出的金额在当月结算后存入余额中，当投资达到10个月后，本金和收益自动退出并存入到余额中",
                                              self.model.name,rate,@"%"]];
    product.top = 0;
    [topView addSubview:product];
    
    UIView * winMethod = [self headerWithTitle:@"收益计算方法" des:@"月月有息的收益按日自动复投，即每月收益会加入投金额中\n\n每月收益计算方式:再投金额*当月天数/365*当月年化利率"];
    winMethod.top = product.bottom;
    [topView addSubview:winMethod];
    
    UIView * detailView = [TMUtils headerViewWithTitle:@"产品详情" color:monthColor];
    detailView.top = winMethod.bottom + 10;
    [topView addSubview:detailView];
    
    topView.height = detailView.bottom;
    self.tableView.tableHeaderView = topView;
}
- (TMMenuControl*)controlWithValue:(NSString*)value name:(NSString*)name{
    if (value.length > 10) {
        value = [value substringToIndex:10];
    }
    TMMenuControl * suishiControl = [[TMMenuControl alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth / 3, 60) value:value name:@"买入期限" showLine:YES];
    [suishiControl addTarget:self action:@selector(onSlectedControl:) forControlEvents:UIControlEventTouchUpInside];
    suishiControl.valueLable.attributedText = nil;
    suishiControl.valueLable.text = value;
    suishiControl.nameLable.textColor = TM_secendTextColor;
    suishiControl.nameLable.text = name;
    return suishiControl;
}

- (void)configBootomView{
    __weak typeof(self) weakSelf =  self;
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 49)
                                                     title:@"立即购买"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:18
                                              cornerRadius:0
                                           backgroundColor:TM_orangeColor
                                           backgroundImage:nil
                                                     image:nil];
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedBuyButton];
    }];
    [self.view addSubview:buyButton];
    buyButton.bottom = [TMUtils tabBarTop]  +49;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.segementButton.cureentIndex == 0) {
        return self.productArray.count;
    }
    if (self.segementButton.cureentIndex == 1) {
        return self.userArray.count;
    }
    if (self.segementButton.cureentIndex == 2) {
        return self.moreArray.count;
    }
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{


    STTableEasyModel * model = self.productArray[indexPath.row];
    return model.height;

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.segementButton.cureentIndex == 0) {
        TMGDetailTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"detailCell"];
        STTableEasyModel * model = self.productArray[indexPath.row];
        cell.model = model;
        return cell;
    }
    if (self.segementButton.cureentIndex == 1) {
        TMGUserTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:@"userCell"];
        cell.model = self.userArray[indexPath.row];
        return cell;
    }
    if (self.segementButton.cureentIndex == 2) {
        TMGFlowMoreTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:@"moreCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
    return nil;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --Action Method
- (void)onSlectedControl:(TMMenuControl*)sender{
    if ([sender.valueLable.text isEqualToString:@"非保本型"]) {
        TMGNotePresentViewController * noteVC = [TMGNotePresentViewController new];
        noteVC.note = @"黄金口袋金价实时参考上海黄金交易所和国际金价，不对金价的涨跌负责。由于金价下跌造成的亏损，需要用户自己承担";
        noteVC.titleString = @"小提示";
        [self presentViewController:noteVC animated:NO completion:nil];
//        [SVProgressHUD showInfoWithStatus:@"黄金口袋金价实时参考上海黄金交易所和国际金价，不对金价的涨跌负责。由于金价下跌造成的亏损，需要用户自己承担"];
    }
}
- (void)onSlectedBuyButton{
    TMGBuyGoldViewController * vc = [[TMGBuyGoldViewController alloc] initWithGoldType:TMGBuyGoldTypeGreenHand];
    vc.model = self.detailModel;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)sendGoodDetailReqeust{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/goods/getGoodsDetails"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (self.model.goodiID.description.length) {
        [dic setObject:self.model.goodiID forKey:@"gid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 self.detailModel = [TMGProductDetailModel mj_objectWithKeyValues:dataDic];
                                                 self.detailModel.cate = self.model.cate.description;
                                                 [self configSubView];
                                                 [self configTableFooter];
                                                 [self reloadData];
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendGoodPeopleBuyReqeust{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/goods/buyGoodsNumbers"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (self.model.goodiID.description.length) {
        [dic setObject:self.model.goodiID forKey:@"gid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSArray * array =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 self.userArray = [NSMutableArray new];
                                                 for (NSDictionary * modelDic in array) {
                                                     TMGBuyUserModel * model = [TMGBuyUserModel mj_objectWithKeyValues:modelDic];
                                                     [self.userArray addObject:model];
                                                 }
                                                 UIButton * button = [self.segementButton buttonWirhIndex:1];
                                                 NSNumber *  num = @(self.userArray.count);
                                                 [button setTitle:[NSString stringWithFormat:@"购买人数%@位",num] forState:UIControlStateNormal];
                                                 [button setTitle:[NSString stringWithFormat:@"购买人数%@位",num] forState:UIControlStateSelected];
                                                 if (self.detailModel) {
                                                     [self reloadData];
                                                 }
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end




